package com.hfuu.demo.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hfuu.demo.domain.entity.User;
import com.hfuu.demo.domain.model.LoginUser;
import com.hfuu.demo.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @description:
 * @author: gunala
 * @date: 2024/2/3 18:06
 */
@Service
//@RequiredArgsConstructor
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

//    private final UserMapper userMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUserName, username));

        //没有查到用户就抛出异常
        if (ObjectUtils.isNull(user)) throw new RuntimeException("用户名或密码错误");
        //查询相关权限
        List<String> permissions = userMapper.getPermissions(user.getId());
        //把数据封装成UserDetails
        return new LoginUser(user,permissions);
    }
}
